package com.cloud.common.support;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

public class CacheConfigurer extends CachingConfigurerSupport {

    private Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
    private RedisCacheConfiguration defaultCacheConfiguration;

    @Autowired
    private RedisConnectionFactory connectionFactory;

    @Autowired
    private Jackson2JsonRedisSerializer jsonRedisSerializer;

    protected void setTimeout(String key, int seconds) {
        if (defaultCacheConfiguration == null) {
            defaultCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                    .entryTtl(Duration.ofMinutes(30))
                    .computePrefixWith(cacheName -> cacheName)
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jsonRedisSerializer));

        }
        configMap.put(key, defaultCacheConfiguration.entryTtl(Duration.ofSeconds(seconds)));
    }

    protected CacheManager createCacheManager() {
        return RedisCacheManager.builder(connectionFactory).withInitialCacheConfigurations(configMap).build();
    }

}
